<template>
  <question-detail 
    :question="question"
    :current-question-index="currentQuestionIndex"
    :question-list="questionList"
    :is-collected="isCollected"
    :is-mastered="isMastered"
    @goToPrevQuestion="goToPrevQuestion"
    @goToNextQuestion="goToNextQuestion"
    @toggleCollect="toggleCollect"
    @toggleMastered="markAsMastered"
    @goToAskAI="goToAskAI"
  />
</template>

<script>
import QuestionDetail from '@/components/question-detail.vue';
import DifficultyTag from '@/components/difficulty-tag.vue';
import UaMarkdown from "@/components/ua2-markdown/ua-markdown.vue";
import config from '@/common/config.js';

export default {
  components: {
    QuestionDetail,
    UaMarkdown,
    DifficultyTag
  },
  data() {
    return {
      question: {
        id: 1,
        title: '',
        categoryName: '',
        difficulty: '★★★',
        views: 0,
        description: '',
        answer: '',
        tags: []
      },
      isCollected: false,
      isMastered: false,
      currentQuestionIndex: 0,
      questionList: [],
      questionId: null,
      categoryId: null
    };
  },
  
  computed: {
    hasPrev() {
      return this.currentQuestionIndex > 0;
    },
    hasNext() {
      return this.currentQuestionIndex < this.questionList.length - 1;
    }
  },

  onLoad(options) {
    console.log("当前页面参数:", options);
    this.questionId = options.questionId;
    this.categoryId = options.categoryId;
    // 如果有categoryId和questionId，则通过接口获取问题详情
    this.loadQuestionsByCategory();
  },

  methods: {
    // 根据分类ID加载问题列表
    loadQuestionsByCategory() {
      // 获取收藏列表
      this.$request('/interview/favorite/list', 'GET')
        .then(res => {
          if (res.code === 200) {
            // 保存收藏问题列表
            this.questionList = res.rows;
            
            // 根据questionId查找当前问题
            const currentIndex = this.questionList.findIndex(q => q.questionId == this.questionId);
            if (currentIndex !== -1) {
              this.currentQuestionIndex = currentIndex;
              this.setQuestionDetailFromApi(this.questionList[currentIndex]);
            } else {
              // 如果没找到对应的问题，默认显示第一个
              this.currentQuestionIndex = 0;
              if (this.questionList.length > 0) {
                this.setQuestionDetailFromApi(this.questionList[0]);
              }
            }
            
            // 检查当前题目是否已被收藏
            this.checkIfCollected();
            // 检查当前题目是否已掌握
            this.checkIfMastered();
          }
        }).catch(err => {
          console.error('获取收藏列表异常:', err);
        });
    },

    // 根据API返回的数据设置问题详情
    setQuestionDetailFromApi(questionData) {
      this.question = {
        id: questionData.questionId,
        title: questionData.content || '暂无标题',
        category: questionData.categoryName || this.question.category,
        difficulty: questionData.difficulty || '中等',
        views: questionData.views || 0,
        answer: questionData.analysis || '暂无答案',
        categoryName: questionData.categoryName || '',
        tags: []
      };
    },


    setCurrentQuestionIndex() {
      // 根据当前题目标题设置索引
      this.currentQuestionIndex = this.questionList.findIndex(
          title => title === this.question.title
      );

      // 如果未找到，默认为第一个
      if (this.currentQuestionIndex === -1) {
        this.currentQuestionIndex = 0;
      }
    },
    
    // 检查当前题目是否已被收藏
    checkIfCollected() {
      // 获取用户收藏列表，检查当前题目是否在其中
      this.$request('/interview/favorite/list', 'GET')
        .then(res => {
          if (res.code === 200 && res.rows) {
            // 检查当前题目是否在收藏列表中
            const isFavorited = res.rows.some(item => item.questionId == this.question.id);
            this.isCollected = isFavorited;
          }
        })
        .catch(err => {
          console.error('获取收藏列表异常:', err);
        });
    },
    
    // 检查当前题目是否已掌握
    checkIfMastered() {
      // 获取用户掌握列表，检查当前题目是否在其中
      this.$request('/interview/mastered/list', 'GET')
        .then(res => {
          if (res.code === 200 && res.rows) {
            // 检查当前题目是否在掌握列表中
            const isMastered = res.rows.some(item => item.questionId == this.question.id);
            this.isMastered = isMastered;
          }
        })
        .catch(err => {
          console.error('获取掌握列表异常:', err);
        });
    },

    goToPrevQuestion() {
      if (this.hasPrev) {
        this.currentQuestionIndex--;
        // 从API获取的数据
        this.setQuestionDetailFromApi(this.questionList[this.currentQuestionIndex]);
        
        // 滚动到页面头部
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 300
        });
        
        // 检查当前题目是否已被收藏
        this.checkIfCollected();
        // 检查当前题目是否已掌握
        this.checkIfMastered();
      }
    },
    
    goToNextQuestion() {
      if (this.hasNext) {
        this.currentQuestionIndex++;
        // 从API获取的数据
        this.setQuestionDetailFromApi(this.questionList[this.currentQuestionIndex]);
        
        // 滚动到页面头部
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 300
        });
        
        // 检查当前题目是否已被收藏
        this.checkIfCollected();
        // 检查当前题目是否已掌握
        this.checkIfMastered();
      }
    },

    toggleCollect() {
      // 切换收藏状态
      const newCollectState = !this.isCollected;
      
      if (newCollectState) {
        // 添加收藏
        this.$request('/interview/favorite/add', 'POST', {
          questionId: this.question.id
        },{'content-type': 'application/json'}).then(res => {
          if (res.code === 200) {
            this.isCollected = newCollectState;
            uni.showToast({
              title: '已收藏',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '收藏失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          console.error('收藏失败:', err);
          uni.showToast({
            title: '收藏失败',
            icon: 'none'
          });
        });
      } else {
        // 取消收藏
        this.$request('/interview/favorite/remove/' + this.question.id, 'DELETE')
          .then(res => {
            if (res.code === 200) {
              this.isCollected = newCollectState;
              uni.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: '取消收藏失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('取消收藏失败:', err);
            uni.showToast({
              title: '取消收藏失败',
              icon: 'none'
            });
          });
      }
    },
    
    // 标记为已掌握功能
    markAsMastered() {
      // 切换掌握状态
      const newMasteredState = !this.isMastered;
      
      if (newMasteredState) {
        // 添加掌握记录
        this.$request('/interview/mastered/add', 'POST', {
          questionId: this.question.id
        }, {'content-type': 'application/json'}).then(res => {
          if (res.code === 200) {
            this.isMastered = newMasteredState;
            uni.showToast({
              title: '标记为已掌握',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: '标记失败',
              icon: 'none'
            });
          }
        }).catch(err => {
          console.error('标记掌握失败:', err);
          uni.showToast({
            title: '标记失败',
            icon: 'none'
          });
        });
      } else {
        // 取消掌握状态（如果需要此功能）
        // 这里暂不实现取消掌握功能，因为通常掌握是单向操作
        uni.showToast({
          title: '已掌握不能取消',
          icon: 'none'
        });
        return;
      }
    },
    
    // 跳转到AI问答页面
    goToAskAI() {
      // 添加安全检查，防止 question 或 question.title 为 undefined
      if (!this.question || !this.question.title) {
        uni.showToast({
          title: '问题信息不完整',
          icon: 'none'
        });
        return;
      }
      
      const title = this.question.title.trim();
      if (!title) {
        uni.showToast({
          title: '问题标题为空',
          icon: 'none'
        });
        return;
      }
      
      try {
        uni.navigateTo({
          url: `/pages/askai/detail?title=${encodeURIComponent(title)}`
        });
      } catch (error) {
        console.error('跳转AI页面失败:', error);
        uni.showToast({
          title: '跳转失败，请重试',
          icon: 'none'
        });
      }
    },

    shareQuestion() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      });
    }
  }
};
</script>

<style>
.container {
  min-height: 100vh;
  padding: 180rpx 15px 15px;
  padding-bottom: 120px;
  background: url("data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiBmaWxsPSJub25lIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMjY3IiBoZWlnaHQ9IjkxOSIgdmlld0JveD0iMCAwIDEyNjcgOTE5Ij48ZGVmcz48bGluZWFyR3JhZGllbnQgeDE9IjAuODUxMjA2NDgxNDU2NzU2NiIgeTE9IjAuOTI1NjAzMTUxMzIxNDExMSIgeDI9IjAuMzA2NjA3NDUxMjE3NTkwMzciIHkyPSIwLjc1NjY1OTIyODgyNTk1NjUiIGlkPSJtYXN0ZXJfc3ZnMF85XzAzNyI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI0Y0RjVGQSIgc3RvcC1vcGFjaXR5PSIxIi8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjRjRGNUZBIiBzdG9wLW9wYWNpdHk9IjAiLz48L2xpbmVhckdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCB4MT0iM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tb3BhY2l0eT0iMSIvPjwvZz48ZyB0cmFuc2Zvcm09Im1hdHJpeCgxLDAsMCwtMSwwLDE0MzApIj48ZWxsaXBzZSBjeD0iMzMzIiBjeT0iNzUwIiByeD0iMzUiIHJ5PSIzNSIgZmlsbD0idXJsKCNtYXN0ZXJfc3ZnMV85XzA0MCkiIGZpbGwtb3BhY2l0eT0iMSIvPjwvZz48ZyB0cmFuc2Zvcm09Im1hdHJpeCgxLDAsMCwtMSwwLDE3MTQpIj48ZWxsaXBzZSBjeD0iNjA4LjUiIGN5PSI4ODEuNSIgcng9IjI0LjUiIHJ5PSIyNC41IiBmaWxsPSJ1cmwoI21hc3Rlcl9zdmcyXzlfMDMzKSIgZmlsbC1vcGFjaXR5PSIxIi8+PC9nPjxnIHRyYW5zZm9ybT0ibWF0cml4KDEsMCwwLC0xLDAsMTc4MikiPjxlbGxpcHNlIGN4PSIxODUiIGN5PSI5MDgiIHJ4PSIxNyIgcnk9IjE3IiBmaWxsPSJ1cmwoI21hc3Rlcl9zdmczXzlfMDMzKSIgZmlsbC1vcGFjaXR5PSIxIi8+PC9nPjxnIHRyYW5zZm9ybT0ibWF0cml4KDEsMCwwLC0xLDAsMTU0NikiPjxlbGxpcHNlIGN4PSIxMDMzIiBjeT0iNzkwIiByeD0iMTciIHJ5PSIxNyIgZmlsbD0idXJsKCNtYXN0ZXJfc3ZnNF85XzAzMykiIGZpbGwtb3BhY2l0eT0iMSIvPjwvZz48ZyB0cmFuc2Zvcm09Im1hdHJpeCgxLDAsMCwtMSwwLDEyOTApIj48ZWxsaXBzZSBjeD0iODgzLjUiIGN5PSI2NzkuNSIgcng9IjM0LjUiIHJ5PSIzNC41IiBmaWxsPSJ1cmwoI21hc3Rlcl9zdmc1XzlfMDMzKSIgZmlsbC1vcGFjaXR5PSIxIi8+PC9nPjwvZz48L3N2Zz4=");
  background-position-y: -260rpx;
  background-size: contain;
  background-repeat: no-repeat;
  background-color: #ffffff;
}

.question-header {
  padding: 10px;
  margin-bottom: 15px;
}

.question-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.question-meta {
  display: flex;
  flex-wrap: wrap;
  font-size: 14px;
  color: #999;
}

.meta-item {
  background-color: #f0f0f0;
  padding: 5px 10px;
  border-radius: 5px;
  margin-right: 10px;
  margin-bottom: 5px;
}

.question-content {
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
}

.content-section {
  margin-bottom: 25px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.section-content {
  font-size: 15px;
  color: #666;
  line-height: 1.6;
}

.section-content.answer {
  background-color: #fdfdfd;
  padding: 0px;
  border-radius: 5px;
}

.tags {
  display: flex;
  flex-wrap: wrap;
}

.tag {
  background-color: #e0f0ff;
  color: #007AFF;
  padding: 5px 10px;
  border-radius: 5px;
  margin-right: 10px;
  margin-bottom: 10px;
  font-size: 14px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 0 10px;
  position: fixed;
  bottom: 10px;
  left: 0;
  right: 0;
  background-color: transparent;
  padding: 10px 15px 20px;
}

.nav-icons {
  display: flex;
  align-items: center;
}

.nav-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px;
}

.nav-icon.disabled {
  opacity: 0.5;
}

.center-icons {
  display: flex;
  align-items: center;
}

.ai-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px;
}

.ai-icon image {
  width: 24px;
  height: 24px;
}

.action-icons {
  display: flex;
}

.action-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 5px;
}
</style>